package com.itxiuyixiu.homework.admin.service;

import com.itxiuyixiu.homework.entity.dto.RewardsAndPunishmentDto;
import com.itxiuyixiu.homework.entity.vo.RewardsAndPunishmentVo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 黄磊
 * @date 2020/4/13
 */
@Service
public class ExcelService {

    @Autowired
    private AdminRewardsAndPublishService adminRewardsAndPublishService;

    public Workbook getCourseRecordExcel() {
        List<RewardsAndPunishmentVo> list = adminRewardsAndPublishService.getRewardsAndPunishmentMessage(new RewardsAndPunishmentDto());
        return getExcel(list);
    }

    private Workbook getExcel(List list) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        if (list.size() == 0) {
            return workbook;
        }
        XSSFSheet sheet = workbook.createSheet();
        Class<?> aClass = list.get(0).getClass();
        Method[] methods_a = aClass.getDeclaredMethods();
        ArrayList<Method> methods = new ArrayList<>();
        for (Method method : methods_a) {
            if (method.getName().matches("(equals)|(toString)|(hashCode)|(getTarget)|(getDecoratedClass)|(getTargetClass)")) {
                continue;
            }
            methods.add(method);
        }
        Object result;
        for (int i = 0; i < list.size(); i++) {
            XSSFRow row = sheet.createRow(i);
            for (int j = 0; j < methods.size(); j++) {
                try {
                    result = methods.get(j).invoke(list.get(i));
                    Cell cell = row.createCell(j , Cell.CELL_TYPE_STRING);
                    cell.setCellValue(String.valueOf(result));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return workbook;
    }
}
